/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.evolution;

import br.com.evolution.util.Update;
import br.com.evolution.util.UpdateEventHandler;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import org.tmatesoft.svn.core.SVNDepth;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.wc.ISVNEventHandler;
import org.tmatesoft.svn.core.wc.SVNClientManager;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNUpdateClient;

/**
 *
 * @author paulo
 */
public class Principal extends javax.swing.JFrame {

    /**
     * Creates new form Principal
     */
    File dsPath = new File(".");
    PrintStream aPrintStream  = new PrintStream(new FilteredStream(new ByteArrayOutputStream()));
    ISVNEventHandler eh = new UpdateEventHandler();
    SVNClientManager cm = SVNClientManager.newInstance();
    Timer timer;
    Timer timer2;

    public Principal() {
        initComponents();
        setLocationRelativeTo(null);
        lblLoading.setVisible(false);
        jScrollPane1.setVisible(false);
        doUpdate();
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnJogar = new javax.swing.JButton();
        lblLoading = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        taSystemOut = new javax.swing.JTextArea();
        lblImagem = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Evolution Games Brasil");
        setBackground(new java.awt.Color(255, 255, 255));
        setResizable(false);
        setType(java.awt.Window.Type.POPUP);
        getContentPane().setLayout(null);

        btnJogar.setText("Jogar");
        btnJogar.setToolTipText("Inicia o jogo");
        btnJogar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnJogarActionPerformed(evt);
            }
        });
        getContentPane().add(btnJogar);
        btnJogar.setBounds(570, 430, 90, 23);

        lblLoading.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/evolution/images/loading.gif"))); // NOI18N
        lblLoading.addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                lblLoadingComponentShown(evt);
            }
        });
        getContentPane().add(lblLoading);
        lblLoading.setBounds(-50, 360, 320, 90);

        jScrollPane1.setBorder(null);
        jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
        jScrollPane1.setEnabled(false);

        taSystemOut.setEditable(false);
        taSystemOut.setColumns(20);
        taSystemOut.setRows(5);
        taSystemOut.setBorder(null);
        jScrollPane1.setViewportView(taSystemOut);

        getContentPane().add(jScrollPane1);
        jScrollPane1.setBounds(38, 450, 330, 16);

        lblImagem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/evolution/images/laucher.png"))); // NOI18N
        getContentPane().add(lblImagem);
        lblImagem.setBounds(0, 0, 700, 483);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-706)/2, (screenSize.height-507)/2, 706, 507);
    }// </editor-fold>//GEN-END:initComponents

    private void btnJogarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnJogarActionPerformed
        try {
            Runtime.getRuntime().exec("interface.bin");
            System.exit(0);
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível iniciar o jogo, verifique!");
        }
    }//GEN-LAST:event_btnJogarActionPerformed

    private void lblLoadingComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_lblLoadingComponentShown
        
    }//GEN-LAST:event_lblLoadingComponentShown

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Principal().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnJogar;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblImagem;
    private javax.swing.JLabel lblLoading;
    private javax.swing.JTextArea taSystemOut;
    // End of variables declaration//GEN-END:variables

    private void checkout() {
        cm.getUpdateClient().setEventHandler(eh);
        SVNUpdateClient uc = cm.getUpdateClient();
        try {
            SVNURL url = SVNURL.parseURIEncoded("https://metin2.googlecode.com/svn/tags/Evolution/");
            uc.doCheckout(url, dsPath, SVNRevision.UNDEFINED, SVNRevision.HEAD, SVNDepth.INFINITY, true);
        } catch (SVNException ex) {
            Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private void doUpdate() {
        iniciar();
        lblLoading.setVisible(true);
        jScrollPane1.setVisible(true);
        btnJogar.setEnabled(false);
    }
    
    class finalizar extends TimerTask{
        public void run(){
            try {
            timer.cancel();
            Update upd = new Update();
            upd.start();
            while (upd.isAlive()){System.setOut(aPrintStream);}
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "Problemas ao efetuar atualização, tente novamente mais tarde.");
            } finally {
                lblLoading.setVisible(false);
                jScrollPane1.setVisible(false);
                btnJogar.setEnabled(true);
            }
        }
    }
    
    class FilteredStream extends FilterOutputStream {
        public FilteredStream(OutputStream aStream) {
            super(aStream);
          }

        public void write(byte b[]) throws IOException {
            String aString = new String(b);
            taSystemOut.append(aString.substring(aString.lastIndexOf("\\"), aString.length()));
            taSystemOut.setCaretPosition(taSystemOut.getText().toString().length()-1);
        }

        public void write(byte b[], int off, int len) throws IOException {
            String aString = new String(b , off , len);
            if (aString.contains("\\")){
                aString = aString.substring(aString.lastIndexOf("\\")+1,aString.length());
                taSystemOut.append(aString);
                taSystemOut.append("\n");
            }
            taSystemOut.setCaretPosition(taSystemOut.getText().toString().length()-1);
        }
    }
    
    public void iniciar(){
        timer = new Timer();
        timer.schedule(new finalizar(), 500);
    }
    
    
}
